package com.meepo.feed.search

import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.meepo.basic.router.RouterManager.FeedModule.FeedSearch_Path
import com.meepo.feed.API
import com.meepo.framework.design.helper.StatusBarHelper
import com.meepo.feed.R
import com.meepo.basic.schema.feed.SearchMetadata
import com.meepo.basic.components.view.MeepoActivity
import com.meepo.feed.Func
import com.meepo.framework.design.recycler.LinearAdapter
import com.meepo.framework.design.recycler.ViewHolder
import com.meepo.sdk.utils.ActivityHelper
import com.meepo.sdk.component.observer.ObserverManager
import com.xiaojinzi.component.anno.RouterAnno
import kotlinx.android.synthetic.main.search_activity.*
import kotlinx.android.synthetic.main.search_view_part_layout.*

@RouterAnno(hostAndPath = FeedSearch_Path)
class SearchActivity : MeepoActivity() {

    private var mSearching: Boolean = false
    private var mSearchResultFragment: SearchResultFragment? = null

    private lateinit var mGuessWordsAdapter: LinearAdapter<SearchMetadata.SearchKeyword>
    private lateinit var mHistoryWordsAdapter: LinearAdapter<SearchMetadata.SearchKeyword>


    private fun applySearchMetadata(metadata: SearchMetadata?) {
        metadata?.let {
            mGuessWordsAdapter.add(it.searchKeywords)
        }
    }

    private fun applySearchHistory(words: List<String>?) {

        if (!words.isNullOrEmpty()) {
            history_ll.visibility = View.VISIBLE
            mHistoryWordsAdapter.refresh(words.map { t -> SearchMetadata.SearchKeyword(id = "", name = t) })
        } else {
            history_ll.visibility = View.GONE
        }
    }

    private fun fetchSearchHistory() {
        presenter.call(
            ObserverManager.applyFunc { Func.fetchSearchHistory() },
            { rsp -> applySearchHistory(rsp) }
        )
    }

    override fun initData() {

        presenter.call(
            API.instance().fetchSearchMetadata(),
            { rsp -> applySearchMetadata(rsp.data) }
        )

        fetchSearchHistory()
    }

    private fun notifySearchingChanged(searching: Boolean, keyword: String) {

        search_sv.setText(keyword)

        this.mSearching = searching

        frame_layout.visibility = if (searching) View.VISIBLE else View.GONE
        search_keyword_nsv.visibility = if (searching) View.GONE else View.VISIBLE

        // 销毁
        mSearchResultFragment?.let {
            ActivityHelper.removeFragment(this.supportFragmentManager, it)
        }

        if (searching) {
            // 搜索结果页
            mSearchResultFragment = SearchResultFragment.instance(keyword)

            ActivityHelper.showFragment(
                this.supportFragmentManager,
                R.id.frame_layout,
                mSearchResultFragment!!
            )
        }

    }

    private fun getAdapter(): LinearAdapter<SearchMetadata.SearchKeyword> {
        return object : LinearAdapter<SearchMetadata.SearchKeyword>(this) {
            override fun getItemLayoutId(item: SearchMetadata.SearchKeyword, position: Int): Int = R.layout.search_activity_item

            override fun bind(item: SearchMetadata.SearchKeyword, holder: ViewHolder, position: Int) {

                holder.getView<TextView>(R.id.keyword_tv)?.let { it ->
                    it.text = item.name
                    it.setOnClickListener {
                        notifySearchingChanged(true, item.name)
                    }
                }
            }
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        StatusBarHelper.immerse(this, search_rl)

        // 默认获取焦点
        search_sv.requestFocus()

        tv_cancel.setOnClickListener {
            if (mSearching) {
                notifySearchingChanged(false, "")
            } else {
                finish()
            }
        }


        // 历史
        history_rv.layoutManager = GridLayoutManager(this, 2)
        mHistoryWordsAdapter = getAdapter()
        history_rv.adapter = mHistoryWordsAdapter

        // 猜你想搜
        guess_rv.layoutManager = GridLayoutManager(this, 2)
        mGuessWordsAdapter = getAdapter()
        guess_rv.adapter = mGuessWordsAdapter


        // 搜索回调
        search_sv.setOnEditorActionListener { textView, _, _ ->

            val keyword = textView.text.toString()

            if (!TextUtils.isEmpty(keyword)) {

                presenter.call(
                    ObserverManager.applyFunc { Func.putSearchHistory(keyword) },
                    { fetchSearchHistory() }
                )

                notifySearchingChanged(true, keyword)

            }

            (textView.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(
                textView.applicationWindowToken,
                0
            )

            true
        }

        // 是否展示推荐
        iv_recommend_toggle.setOnClickListener {
            onRecommendBarToggle()
        }
        show_recommend_ll.setOnClickListener {
            onRecommendBarToggle()
        }

        // 删除历史
        delete_iv.setOnClickListener {

            presenter.call(
                ObserverManager.applyFunc { Func.clearSearchHistory() },
                { fetchSearchHistory() }
            )
        }
    }

    private fun onRecommendBarToggle() {
        guess_ll.visibility = if (guess_ll.visibility == View.VISIBLE) View.GONE else View.VISIBLE
        show_recommend_ll.visibility =
            if (guess_ll.visibility == View.VISIBLE) View.GONE else View.VISIBLE
    }


    override fun setUpContentLayout(): Int = R.layout.search_activity
}